<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级" prop="classesId" label-width="" style="width:240px">
        <el-select style="width: 240px" v-model="queryParams.classesId" @change="changeStudentList($event)" placeholder="请选择班级" :style="{width: '100%'}" >
          <el-option v-for="(item, index) in classesList" :key="index" :label="item.className"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学员" prop="userId" style="width:240px">
        <el-select style="width: 240px" v-model="queryParams.userId" placeholder="选择学员" :style="{width: '100%'}" >
          <el-option v-for="(item, index) in studentList" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['teaching:interview_mastery:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teaching:interview_mastery:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['teaching:interview_mastery:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="interview_masteryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学员" align="center" prop="username" />
      <el-table-column label="技能平均得分" align="center" prop="avgScore" >
        <template #default="scope">
          {{scope.row.avgScore}}/100
        </template>
      </el-table-column>
      <el-table-column label="沟通得分" align="center" prop="communicationScore">
        <template #default="scope">
          {{scope.row.communicationScore}}/100
        </template>
      </el-table-column>
      <el-table-column label="沟通情况" align="center" prop="communicationInterview_mastery">
        <template #default="scope">
          <dict-tag :options="ya_communication_mastery" :value="scope.row.communicationMastery ? scope.row.communicationMastery.split(',') : []"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="是否总结" align="center" prop="summarized">
        <template #default="scope">
          <dict-tag :options="ya_summarized" :value="scope.row.summarized"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="日期" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['teaching:interview_mastery:edit']"
          >详情</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['teaching:interview_mastery:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改面试掌握情况记录对话框 -->
    <el-dialog :title="title" v-model="open" fullscreen >
      <el-tabs type="border-card">
        <el-tab-pane label="面试题掌握情况">
          <el-form v-if="title!='修改面试掌握情况记录'"  :model="queryInterviewParams" ref="queryInterviewRef" :inline="true"  label-width="68px">
            <el-form-item label="班级" prop="classesId" style="width:240px">
              <el-select  style="width: 240px" v-model="queryInterviewParams.classesId" clearable @change="changeStudentList($event)" placeholder="请选择班级" :style="{width: '100%'}" >
                <el-option v-for="(item, index) in classesList" :key="index" :label="item.className"
                           :value="item.id" ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="学员" prop="userId" style="width:240px">
              <el-select style="width: 340px" @change="getMasteryDegreeList" v-model="queryInterviewParams.userId" clearable placeholder="学员" :style="{width: '100%'}" >
                <el-option v-for="(item, index) in studentList" :key="index" :label="item.name"
                           :value="item.id" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-divider></el-divider>
            <div v-show="queryInterviewParams.userId">
              <el-form-item label="关键字" prop="question">
                <el-input
                  v-model="queryInterviewParams.question"
                  placeholder="请输入面试题"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="阶段" prop="stage" style="width:200px">
                <el-select v-model="queryInterviewParams.stage"  @change="getMasteryDegreeList" placeholder="请选择阶段" clearable style="width:200px">
                  <el-option
                    v-for="dict in sys_stage"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="重要性" prop="importance" style="width:200px">
                <el-select v-model="queryInterviewParams.importance" @change="getMasteryDegreeList" placeholder="请选择重要性" clearable style="width:200px">
                  <el-option
                    v-for="dict in ya_importance"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="及格" prop="importance" style="width:200px">
                <el-select v-model="queryInterviewParams.qualified"  @change="getMasteryDegreeList" placeholder="请选择阶段" clearable style="width:200px">
                  <el-option
                    v-for="dict in ya_qualified"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="上一次" title="只看上一次回答情况" prop="importance" >
                <el-radio v-model="queryInterviewParams.onlyLast" @change="getMasteryDegreeList" :label="true">是</el-radio>
                <el-radio v-model="queryInterviewParams.onlyLast" @change="getMasteryDegreeList" :label="false">否</el-radio>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" icon="Search" @click="getMasteryDegreeList">搜索面试记录</el-button>
                <el-button icon="Refresh" @click="resetMasteryDegreeQuery">重置</el-button>
              </el-form-item>
            </div>
          </el-form>
          <el-table v-show="queryInterviewParams.userId" style="width: 100%" :data="interview_masteryDegreeList" v-loading="masteryDegreeListLoading">
            <el-table-column label="阶段" align="center"  prop="stage">
              <template #default="scope">
                <dict-tag :options="sys_stage" :value="scope.row.stage"/>
              </template>
            </el-table-column>
            <el-table-column label="面试题" align="center"   prop="question" />
            <!--            <el-table-column label="面试题222" align="center"   prop="answer" />-->
            <el-table-column label="重要性" align="center"  prop="importance">
              <template #default="scope">
                <dict-tag :options="ya_importance" :value="scope.row.importance"/>
              </template>
            </el-table-column>
            <el-table-column label="上次提问人" align="center"  prop="lastCreateBy"/>
            <el-table-column label="上次掌握程度" align="center" prop="hisDegreeList">
              <template #default="scope">
                <dict-tag :options="ya_mastery_degree" :value="scope.row.hisDegree"/>
              </template>
            </el-table-column>
            <el-table-column label="上次得分" align="center"  prop="hisDegreeList">
              <template #default="scope">
                {{scope.row.score}}/10
              </template>
            </el-table-column>

            <el-table-column  label="参考答案" type="expand" >
              <template #default="scope" >
                <mavon-editor v-model="scope.row.answer" :subfield="false" defaultOpen="preview" :editable="false" :toolbarsFlag="false"/>
              </template>
            </el-table-column>
            <el-table-column label="总结" align="center"   prop="summarize" />
            <el-table-column label="掌握程度" align="left"  prop="degree" v-if="title!='修改面试掌握情况记录'">
              <template #default="scope">
                <el-checkbox-group  v-model="selectedInterviewList">
                  <el-checkbox
                    v-for="dict in ya_mastery_degree"
                    :key="scope.row.id+ ','   +dict.value"
                    :label="scope.row.id+ ','   +dict.value" :disabled="checkDisabled(scope.row.id,dict.value)">
                    {{dict.label}}
                  </el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="沟通情况/备注">
          <el-form  ref="formRef" :model="form"  label-width="80px">
            <el-form-item label="沟通情况" prop="communicationMastery">
              <el-checkbox-group v-model="form.communicationMastery">
                <el-checkbox
                  v-for="dict in ya_communication_mastery"
                  :key="dict.value"
                  :label="dict.value">
                  {{dict.label}}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="title!='修改面试掌握情况记录'">提交反馈</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="mastery">
import {
  listMastery,
  masteryQuery,
  getMastery,
  addMastery,
  updateMastery,
  delMastery
} from "@/api/teaching/mastery";

import {listInterview} from "@/api/teaching/interview";
import {listClass} from "@/api/teaching/class";
import {listStudent} from "@/api/teaching/student";

const { proxy } = getCurrentInstance();
const { sys_stage } = proxy.useDict('sys_stage')
const { ya_importance } = proxy.useDict('ya_importance')
const { ya_communication_mastery } = proxy.useDict('ya_communication_mastery')
const { ya_mastery_degree } = proxy.useDict('ya_mastery_degree')
const { ya_qualified } = proxy.useDict('ya_qualified')
const { ya_summarized } = proxy.useDict('ya_summarized')


// 表单校验
const checkCommunicationInterview_mastery = (rule, value, callback) => {
  if (value.length == 0) {
    proxy.$modal.msgError("请填写沟通情况,在下一个Tab中");
    return callback(new Error('请填写沟通情况'));
  } else {
    callback();
  }
};

// 数据
const selectedInterviewList = ref([]);
const studentList = ref([]);
const classesList = ref([]);
const interview_masteryDegreeList = ref([]);
const loading = ref(true);
const masteryDegreeListLoading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const interview_masteryList = ref([]);
const title = ref("");
const open = ref(false);

const data = reactive({
  form: {
    id: null,
    communicationMastery: [],
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    classesId: null,
    userId: null,
    summarized: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communicationInterview_mastery: null,
    userId: null,
  },
  queryInterviewParams: {
    pageNum: 1,
    pageSize: 10,
    stage: null,
    qualified: null,
    question: null,
    answer: null,
    knowledgePoint: null,
    importance: null,
    onlyLast: false
  },
  rules: {
    communicationInterview_mastery: [
      {validator: checkCommunicationInterview_mastery, trigger: "blur"}
    ],
  }
});

const { queryParams, form, queryInterviewParams, rules } = toRefs(data);

// 引用
const queryRef = ref();
const queryInterviewRef = ref();
const formRef = ref();

/** 生命周期 */
onMounted(() => {
  getList();
  getClassesList();
});

/** 方法 */
function checkDisabled(questionid, selectedValue) {
  let findElement = questionid + "," + 1;
  //是否选中无概念
  let target = selectedInterviewList.value.find(v => v.includes(findElement));
  if (target) {
    return target && selectedValue != 1;
  }
  //是否选中模糊
  findElement = questionid + "," + 2;
  target = selectedInterviewList.value.find(v => v.includes(findElement));
  if (target) {
    return target && selectedValue != 2;
  }
  return false;
}

function changeStudentList(classesId) {
  queryParams.value.userId = null;
  listStudent(classesId).then(response => {
    studentList.value = response.rows;
  });
}

function getClassesList() {
  listClass().then(response => {
    classesList.value = response.rows;
  });
}

/** 查询面试掌握情况记录列表 */
function getMasteryDegreeList() {
  if (!queryInterviewParams.value.userId) {
    proxy.$modal.msgWarning("请依次选择[班级-学员]");
    return;
  }
  masteryDegreeListLoading.value = true;
  listInterview(queryInterviewParams.value).then(response => {
    //处理一下上次掌握情况
    for (let i = 0; i < response.rows.length; i++) {
      if (response.rows[i].hisDegree && response.rows[i].hisDegree.includes(",")) {
        response.rows[i].hisDegree = response.rows[i].hisDegree.split(",");
      }
    }
    interview_masteryDegreeList.value = response.rows;
    masteryDegreeListLoading.value = false;
  });
}

/** 查询面试掌握情况记录列表 */
function getList() {


  loading.value = true;
  if(title.value === "添加面试掌握情况记录"){
    masteryQuery(queryInterviewParams.value).then(response => {
      interview_masteryList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }else{
    listMastery(queryParams.value).then(response => {
      console.log(response.rows)
      interview_masteryList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }



}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  interview_masteryDegreeList.value = [];
  resetInterview_masteryDegreeQuery();
  selectedInterviewList.value = [];
  form.value = {
    id: null,
    communicationMastery: [],
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    classesId: null,
    userId: null
  };
  // 使用 nextTick 确保 DOM 更新完成
  nextTick(() => {
    proxy.resetForm("formRef");
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetInterview_masteryDegreeQuery() {
  queryInterviewParams.value = {
    importance: null,
    question: null,
    stage: null,
    classesId: null,
    userId: null,
    onlyLast: false,
    qualified: null
  };
  proxy.resetForm("queryInterviewRef");
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加面试掌握情况记录";
  masteryDegreeListLoading.value = false;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  masteryDegreeListLoading.value = true;
  getMastery(id).then(response => {
    if (response.data.communicationInterview_mastery && response.data.communicationInterview_mastery.includes(",")) {
      response.data.communicationInterview_mastery = response.data.communicationInterview_mastery.split(",");
    }

    const detailList = response.data.interview_masteryDetailList || [];

    console.log(response.data)
    //处理一下上次掌握情况
    /*for (let i = 0; i < detailList.length; i++) {
      if (response.data.interview_masteryDetailList[i].hisDegree && response.data.interview_masteryDetailList[i].hisDegree.includes(",")) {
        response.data.interview_masteryDetailList[i].hisDegree = response.data.interview_masteryDetailList[i].hisDegree.split(",");
      }
    }*/
    for (let i = 0; i < detailList.length; i++) {
      if (detailList[i].hisDegree && detailList[i].hisDegree.includes(",")) {
        detailList[i].hisDegree = detailList[i].hisDegree.split(",");
      }
    }
    console.log(id)
    queryInterviewParams.value.userId = id;
    // interview_masteryDegreeList.value = response.data.interview_masteryDetailList;
    interview_masteryDegreeList.value = detailList;
    form.value = response.data;
    open.value = true;
    title.value = "修改面试掌握情况记录";
    masteryDegreeListLoading.value = false;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMastery(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        if(!queryInterviewParams.value.userId){
          proxy.$modal.msgWarning("选择一名学员");
          return;
        }
        if(selectedInterviewList.value.length===0){
          proxy.$modal.msgWarning("至少一条面试记录");
          return;
        }
        console.log(form.value);
        let submitForm = JSON.parse(JSON.stringify(form.value));
        console.log(submitForm);
        submitForm.communicationMastery = form.value.communicationMastery.join(",");
        submitForm.userId = queryInterviewParams.value.userId;
        submitForm['selectedInterviewList'] = selectedInterviewList.value;
        addMastery(submitForm).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除面试掌握情况记录编号为"' + _ids + '"的数据项？').then(function () {
    return delMastery(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('teaching/interview_mastery/export', {
    ...queryParams.value
  }, `interview_mastery_${new Date().getTime()}.xlsx`);
}
</script>
